import { css } from "@emotion/css";
import {
  Breadcrumb,
  Button,
  Form,
  Input,
  Message,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Tooltip,
} from "@arco-design/web-react";
import { useState } from "react";
import { usePagination } from "../../hooks/usePagination.ts";
import { CameraInfoModal } from "../../components/CameraInfoModal";
import { useAPI } from "../../hooks/useAPI.ts";
import { useQuery } from "react-query";
import {
  CameraStatus,
  SearchCameraListParams,
} from "../../api/types/camera.ts";
import { useAsyncFn, useDebounce } from "react-use";
import { Link } from "../../components/Link";
import {
  IconDelete,
  IconPen,
  IconPlusCircle,
  IconRefresh,
  IconRight,
} from "@arco-design/web-react/icon";
import { CameraColorMap, CameraTextMap } from "../../hooks/useCameraStatus.ts";

const Option = Select.Option;
const options = [
  { label: "正常", value: CameraStatus.normal },
  { label: "离线", value: CameraStatus.abnormal },
];

export default function Camera() {
  const api = useAPI();
  const [formRef] = Form.useForm<SearchCameraListParams>();
  const { pagination, pageNum, pageSize, setTotal, resetPage } =
    usePagination();

  const [cameraId, setCameraId] = useState<number>();
  const [isOpenAddCameraModal, setIsOpenAddCameraModal] = useState(false);
  const [isOpenCameraInfoModal, setIsOpenCameraInfoModal] = useState(false);
  const [searchValues, setSearchValues] =
    useState<SearchCameraListParams | null>(null);

  const { data, isLoading, refetch } = useQuery(
    ["getCameraList", pageNum, pageSize],
    async () => {
      try {
        const values = searchValues || {};
        const response = await api.getCameraList({
          ...values,
          pageNum,
          pageSize,
        });
        setTotal(response.data?.data.total || 0);
        return response.data?.data.rows.map((row: any, index: number) => ({
          index: index + 1 + (pageNum - 1) * pageSize, // Add index starting from 1 // Add index starting from 1
          ...row,
        }));
      } catch (error) {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      }
    }
    // {
    //   onSuccess: (data) => {
    //     setTotal(data?.length || 0);
    //   },
    // },
  );

  const [, onSearch] = useAsyncFn(async (values: SearchCameraListParams) => {
    resetPage();
    setSearchValues(values);
    await refetch();
  });

  useDebounce(
    () => {
      onSearch(searchValues as SearchCameraListParams);
    },
    300,
    [searchValues]
  );
  return (
    <div>
      <CameraInfoModal
        title="添加摄像头"
        visible={isOpenAddCameraModal}
        onClose={() => {
          setIsOpenAddCameraModal(false);
        }}
        onSuccess={async () => {
          setIsOpenAddCameraModal(false);
          Message.success("添加摄像头成功");
          await refetch();
        }}
      />
      <CameraInfoModal
        title="编辑摄像头"
        visible={isOpenCameraInfoModal}
        isEdit={true}
        cameraId={cameraId}
        onClose={() => {
          setIsOpenCameraInfoModal(false);
        }}
        onSuccess={async () => {
          setIsOpenCameraInfoModal(false);
          Message.success("编辑摄像头成功");
          await refetch();
        }}
      />
      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
          margin-bottom: 20px;
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/deviceManagement/camera"
            style={{
              textDecoration: "none",
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            摄像头管理
          </Link>
        </Breadcrumb.Item>
      </Breadcrumb>
      <div
        className={css`
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        `}
      >
        <Form form={formRef} onSubmit={onSearch} layout="inline">
          <Form.Item field="key" label="搜索：">
            <Input.Search
              value={searchValues?.key}
              onChange={(v) => setSearchValues({ ...searchValues, key: v })}
              placeholder="请输入关键字"
              allowClear
              style={{ width: "200px" }}
            />
          </Form.Item>
          <Form.Item field="status" label="状态" wrapperCol={{ span: 14 }}>
            <Select
              onChange={(v) => setSearchValues({ ...searchValues, status: v })}
              placeholder="请选择"
              allowClear
              style={{ width: "200px" }}
            >
              {options.map((option, index) => (
                <Option key={index} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                setSearchValues({
                  ...searchValues,
                  key: "",
                  status: undefined,
                });
              }}
            >
              <IconRefresh />
              重置
            </Button>
          </Form.Item>
        </Form>
        <Button
          type="primary"
          size="small"
          onClick={(e) => {
            e.preventDefault();
            setIsOpenAddCameraModal(true);
          }}
        >
          <IconPlusCircle />
          添加摄像头
        </Button>
      </div>
      <Table
        data={data}
        loading={isLoading}
        className={css`
          margin-top: 16px;
        `}
        rowKey="index"
        pagination={pagination}
        columns={[
          {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            sorter: (a, b) => a.index - b.index,
          },
          {
            title: "摄像头名称",
            dataIndex: "camera_name",
            key: "camera_name",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "摄像头IP",
            dataIndex: "ip",
            key: "ip",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "通道号",
            dataIndex: "channel",
            key: "channel",
            render: (record: string) => `D${record}`,
            sorter: (a, b) => a.channel - b.channel,
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "在线状态",
            dataIndex: "status",
            key: "status",
            render: (record: CameraStatus) => (
              <Tag color={CameraColorMap[record]}>{CameraTextMap[record]}</Tag>
            ),
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "绑定位置",
            dataIndex: "building_name",
            key: "building_name",
            render: (buildingName, rowData) => {
              const { room_name, floor_name } = rowData;
              if (!buildingName || !room_name || !floor_name)
                return <Tag color="orange"> 未绑定 </Tag>;
              return `${buildingName}-${floor_name}-${room_name}`;
            },
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
          },
          {
            title: "操作",
            dataIndex: "id",
            key: "actions",
            align: "center", // Center the cell content
            headerAlign: "center", // Center the header content
            render: (record) => (
              <Space>
                <Tooltip content="编辑">
                  <Button
                    size="small"
                    shape="circle"
                    type="outline"
                    icon={<IconPen />}
                    onClick={(e) => {
                      e.preventDefault();
                      setCameraId(record);
                      setIsOpenCameraInfoModal(true);
                    }}
                  />
                </Tooltip>
                <Popconfirm
                  focusLock
                  title="请确认"
                  content="是否删除该摄像头？"
                  onOk={async () => {
                    await api.deleteCamera(record);
                    await refetch();
                  }}
                >
                  <Tooltip content="删除">
                    <Button
                      size="small"
                      shape="circle"
                      type="outline"
                      icon={<IconDelete />}
                    />
                  </Tooltip>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />
    </div>
  );
}
